package com.ebring.shareEducation.service.impl;

import com.ebring.shareEducation.bean.RoleMenu;
import com.ebring.shareEducation.bean.RoleMenuMiddle;
import com.ebring.shareEducation.dao.RoleMenuMapper;
import com.ebring.shareEducation.dao.RoleMenuMiddleMapper;
import com.ebring.shareEducation.service.RoleMenuMiddleService;
import com.ebring.shareEducation.utils.RspMsg;
import com.ebring.shareEducation.utils.UuidUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RoleMenuMiddleServiceImpl implements RoleMenuMiddleService {

    @Autowired
    private RoleMenuMiddleMapper roleMenuMiddleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     *查询角色对应的菜单
     */
    @Override
    public RspMsg<List<RoleMenuMiddle>> selectRoleMenuMiddleId(String roleId) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<RoleMenuMiddle> roleMenuList= roleMenuMiddleMapper.findRoleMenuIdListByRoleId(roleId);
        if (roleMenuList.isEmpty() || roleMenuList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到数据");
            return rspMsg;

        }

        PageInfo<RoleMenuMiddle> pageInfo = new PageInfo<>(roleMenuList);
        map.put("total", pageInfo.getTotal());
        map.put("userList", roleMenuList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }
    /**
     *为角色分配菜单
     */
    @Override
    public  RspMsg<RoleMenu> insertRoleMenu(String roleId, String[] menuIds) {
        RspMsg rspMsg = new RspMsg();
        // 先删除用户已有的一些菜单
        int j =roleMenuMiddleMapper.deleteRoleMenu(roleId);
        if (j == 0) {
            rspMsg.setError();
            rspMsg.setMsg("删除失败");
            return rspMsg;
        }
        // 插入表中
        RoleMenu roleMenu = null;
        for (int i = 0; i < menuIds.length; i++) {
            roleMenu = new RoleMenu();
            roleMenu.setId(UuidUtils.getUUID());
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuIds[i]);
            int k = roleMenuMapper.insertSelective(roleMenu);
            if ( k== 0) {
                rspMsg.setError();
                rspMsg.setMsg("插入失败");
                return rspMsg;
            }
        }
        rspMsg.setOK();
        return rspMsg;
    }
}
